package com.itheima.reggie.web.controller;

import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.web.R;
import com.itheima.reggie.entity.dto.employee.EmpAddDTO;
import com.itheima.reggie.entity.dto.employee.EmpUpdateDTO;
import com.itheima.reggie.entity.dto.LoginDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 员工控制层
 *
 * @Name : EmployeeController
 * @Author : WuQiang
 * @Date : 2022-08-08 19:41
 * @Description : 员工控制层
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param dto
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginDTO dto, HttpSession session) {
        log.info("员工登录");
        R r = employeeService.login(dto);
        Employee employee = (Employee) r.getData();
        //将信息存入session
        session.setAttribute("emp", employee.getId());
        return r;
    }

    /**
     * 员工登出
     *
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session) {
        log.info("员工登出");
        session.removeAttribute("emp");
        return R.success("登出成功");
    }

    /**
     * 分页查询
     *
     * @param page     当前页
     * @param pageSize 页面大小
     * @param name     模糊查询
     * @return
     */
    @GetMapping("/page")
    public R getEmpByPage(Long page, Long pageSize, String name) {
        return employeeService.getEmpByPage(page, pageSize, name);
    }

    /**
     * 新增员工
     *
     * @param dto
     * @return
     */
    @PostMapping
    public R saveEmp(@RequestBody EmpAddDTO dto) {
        Boolean flag = employeeService.saveEmp(dto);
        if (flag) {
            return R.success("新增员工成功");
        }
        return R.error("新增员工失败");
    }

    /**
     * 根据id查询并回显数据
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R getById(@PathVariable Long id){
        if (ObjectUtils.isEmpty(id)) {
            return  R.error("参数非法");
        }
        Employee employee = employeeService.getById(id);
        //数据脱敏处理
        employee.setStatus(null);
        employee.setPassword(null);
        if (employee == null){
            return R.error("该用户不存在");
        }
        return R.success("查询成功",employee);
    }

    /**
     * 修改员工信息
     * @param dto
     * @return
     */
    @PutMapping
    public R update(@RequestBody EmpUpdateDTO dto){
        Boolean flag = employeeService.updateEmp(dto);
        if (flag){
            return R.success("修改员工信息成功");
        }
        return R.error("修改员工信息失败");
    }
}
